<template>
  <div class="container">
    <div class="app-container">
      <!-- 组织架构 -->
      <el-tree default-expand-all :data="depts" :props="defaultProps">
        <!-- 节点结构 -->
        <template #default="{ data }">
          <el-row style="width: 100%">
            <el-col :span="20">{{ data.name }}</el-col>
            <el-col :span="4">
              <el-col :span="12"><span class="tree-manager">{{ data.managerName||'无' }}</span></el-col>

              <el-dropdown @command="handleCommand($event,data.id)">
                <span class="el-dropdown-link">
                  操作
                  <i class="el-icon-arrow-down " />
                </span>
                <!-- 下拉菜单选项 -->
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                    <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                    <el-dropdown-item command="del">删除部门</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
      <el-dialog :visible.sync="showAddDept" :title="title" @close="handleClose">
        <el-form ref="addForm" label-width="100px" :model="addForm" :rules="rules">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="addForm.code" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="managerId">
            <el-select v-model="addForm.managerId" placeholder="请输入">
              <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="addForm.introduce" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-form>
        <div style="display: flex;justify-content: center;">
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="handleClose">取消</el-button>
        </div>
        <!-- 具名插槽 -->
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getManagerList, addDepartments, getDepartDetail, editDepartment, deleteDepartment, getDepartments } from '@/api/department'
import { transList2TreeData } from '@/utils'

export default {
  name: 'Department',
  data() {
    return {
      depts: [
      //   {
      //   name: '传智教育',
      //   children: [
      //     { name: '总裁办' },
      //     { name: '行政部' },
      //     { name: '财务部' }
      //   ]
      // }
      ],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      list: [], // 备份一个部门列表数据  用于查询是否重复
      showAddDept: false,
      managerList: [], // 部门负责人列表(需要请求后端数据)
      addForm: {
        name: '',
        code: '',
        managerId: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称的长度为2-10个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let temp = this.list
              if (this.addForm.id) {
                temp = temp.filter(item => item.id !== this.addForm.id) // 排除自己  留下其他人
              }
              if (temp.some(item => item.name === value)) {
                callback(new Error('部门名称已存在'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 2, max: 10, message: '部门编码的长度为2-10个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let temp = this.list
              if (this.addForm.id) {
                temp = temp.filter(item => item.id !== this.addForm.id)
              }
              if (temp.some(item => item.code === value)) {
                callback(new Error('和已有部门编码重复'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        managerId: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 100, message: '部门介绍的长度为1-100个字符', trigger: 'blur' }
        ]
      },
      parentId: null // 父级id(用于添加部门)
    }
  },
  computed: {
    title() {
      return this.addForm.id ? '编辑部门' : '添加部门'
    }
  },
  created() {
    this.getManagerList()
    this.getDepartment() // 调用获取数据的接口
  },
  methods: {
    async getDepartment() {
      const result = await getDepartments()
      this.list = result
      this.depts = transList2TreeData(result, 0)
    },
    handleCommand(type, id) {
      if (type === 'add') {
        // 添加
        this.showAddDept = true
        this.parentId = id // 存一下这行部门的id => 这是即将添加的子部门的pid
      }
      if (type === 'edit') {
        // 编辑
        this.showAddDept = true // 显示弹窗
        this.parentId = id // 存一下这行部门的id => 这是即将添加的子部门的pid
        this.getDepartDetail()
      }
      if (type === 'del') {
        // 删除
        this.parentId = id // 存id =》将来删除
        // this.deleteDepartment()
        this.$confirm('此操作将永久删除该部门, 是否继续?', '警告', {
          cancelButtonText: '我想想', // 配置取消按钮文字
          type: 'warning' // 配置图标
        }).then(() => {
          this.deleteDepartment()
        }).catch(() => {
          console.log('取消了')
        })
      }
    },
    async deleteDepartment() {
      await deleteDepartment(this.parentId)
      this.getDepartment()
      this.$message.success('删除成功')
    },
    async getDepartDetail() {
      const res = await getDepartDetail(this.parentId)
      //  数据回显   将后端返回的详情数据  赋值  给表单   表单和页面做了双绑
      this.addForm = res
    },
    getManagerList() {
      getManagerList().then(res => {
        this.managerList = res
      })
    },
    submit() {
      // 整体校验 =>  封装api接口 请求后端 => 提示 => 关闭对话框 => 清空 => 重新请求重新渲染(调用函数)
      this.$refs.addForm.validate(async(isOk) => {
        if (isOk) {
          if (this.addForm.id) {
            await editDepartment(this.addForm)
            this.$message.success('修改成功')
          } else {
            await addDepartments({
              ...this.addForm,
              pid: this.parentId
            })
            this.$message.success('添加部门成功')
          }
          this.getDepartment()
          this.handleClose()
        }
      })
    },
    handleClose() {
      this.showAddDept = false
      this.$refs.addForm.resetFields()
      this.addForm = {
        name: '',
        managerId: '',
        code: '',
        introduce: ''
      }
    }
  }
}
</script>
